<?php

namespace App\Middleware\ws;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Service\Users\UsersService;
use Firebase\JWT\JWT;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use App\Model\User;
use Hyperf\HttpServer\Contract\ResponseInterface as Response;
use Hyperf\Di\Annotation\Inject;
use Hyperf\WebSocketServer\Context;
use Hyperf\WebSocketServer\Sender;

class UserSocketAuthMiddleware implements MiddlewareInterface
{
    /**
     * @Inject
     * @var Response
     */
    protected $response;

    /**
     * @Inject()
     * @var Admin
     */
    protected $adminModel;


    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {

        if (Context::has('uid')) {
            return $handler->handle($request);
        }

        $token = $request->getQueryParams()['token'] ?? '';

        if($token){

        }

        $token = trim(ltrim($request->getHeaderLine('Authori-zation'), 'Bearer'));
        list($headb64, $bodyb64, $cryptob64) = explode('.', $token);
        $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($bodyb64));
        $uid = $payload->jti->id;

        if (!$uid) {
            //登录失效
            err('token失效', ErrorCode::TOEKN_INVALID);
        }
        //取出用户id
        Context::set('uid', $uid);
        return $handler->handle($request);
    }

}